package com.spark.check

import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.check.model.ToBeTaskModel
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.toast
import com.spark.common.ext.wrapIO
import com.spark.common.model.ResultModel
import com.spark.common.net.Http
import com.spark.common.widget.RejectAlert
import com.spark.common.widget.Switcher
import kotlinx.android.synthetic.main.frag_to_accept.*

/**
 * 待接受任务
 */
class ToAcceptFragment : BaseFragment() {
    private var taskId = ""
    private lateinit var acceptAdapter: AcceptAdapter
    private val accItems = mutableListOf<SubmitWrapModel>()

    companion object {
        fun newInstance(id: String): ToAcceptFragment {
            val fragment = ToAcceptFragment()
            val args = Bundle()
            args.putString(Const.qr_taskid, id)
            fragment.arguments = args
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.frag_to_accept
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        taskId = arguments?.getString(Const.qr_taskid) ?: ""
        acceptAdapter = AcceptAdapter(R.layout.item_accepts)
        recy_aceepts.adapter = acceptAdapter
        recy_aceepts.layoutManager = LinearLayoutManager(context)
        recy_aceepts.isNestedScrollingEnabled = false

        acceptAdapter.addData(mutableListOf(
                ToBeTaskModel.Data.Item(),
                ToBeTaskModel.Data.Item(),
                ToBeTaskModel.Data.Item(),
                ToBeTaskModel.Data.Item(),
                ToBeTaskModel.Data.Item(),
                ToBeTaskModel.Data.Item()
        ))
        acceptAdapter.addSwitchChangeListener { switcher, state, pos, item ->
            activity?.apply {
                if (state == Switcher.State.OFF) {
                    RejectAlert.Builder(this, "拒绝理由")
                            .affirm("确定 ") { d, text ->
                                if (text.isNullOrBlank()) toast("请输入拒绝理由")
                                else {
                                    acceptAdapter.data[pos].rejectremark = text ?: ""
                                    acceptAdapter.notifyDataSetChanged()
                                    d.dismiss()
                                    switcher.update(state)
                                }
                            }
                            .cancel("取消") { d, i ->
                                d.dismiss()
                                item.state = false
                                acceptAdapter.notifyItemChanged(pos)
                            }
                            .create()
                            .show()
                }
            }

        }
        tv_title.text = "待接受任务"
        iv_back.setOnClickListener { activity?.finish() }
        // 提交
        tv_submit.setOnClickListener {
            acceptAdapter.data.forEach {
                val submitItem = SubmitWrapModel("${it.itemId}", it.state, it.rejectremark)
                accItems.add(submitItem)
            }
            submit()
        }
    }

    /**
     * 获取待接受任务
     */
    fun fetchToAcceptTasks() {
        val params = mutableMapOf(
                Pair(Const.qr_taskid, taskId)
        )
        activity?.apply {
            Http.request()
                    .rxPost("${Const.base_url}${Const.act_task_detail}", params)
                    .wrapIO()
                    .subscribe(
                            {
                                Gson().fromJson(it, ToBeTaskModel::class.java)?.apply {
                                    if (code == "200") {
                                        acceptAdapter.addData(data.items)
                                    }
                                }
                            },
                            {
                                it.printStackTrace()
                                hideLoader()
                            },
                            {
                                hideLoader()
                            },
                            {
                                dispose = it
                                loading()
                            }
                    )
        }
    }

    /**
     * 提交
     */
    fun submit(status: String = "", remark: String = "") {
        val params = mutableMapOf(
                Pair(Const.qr_taskid, "$id"),
                Pair(Const.qr_status, status),
                Pair(Const.qr_remark, remark)
        )
        activity?.apply {
            Http.request()
                    .rxPost("${Const.base_url}${Const.act_accep_task_post}", params)
                    .wrapIO()
                    .subscribe(
                            {
                                Gson().fromJson(it, ResultModel::class.java)?.apply {
                                    if (code == "200") {
                                        toast("提交成功")
                                        pop()
                                    } else {
                                        toast(msg)
                                    }
                                }
                            },
                            {
                                it.printStackTrace()
                                hideLoader()
                            },
                            {
                                hideLoader()
                            },
                            {
                                dispose = it
                                loading("提交中...")
                            }
                    )
        }
    }
}

/**
 * 将要提交的接受信息
 */
class SubmitWrapModel(
        var id: String = "",
        var state: Boolean = false,
        var remark: String = ""
)

class AcceptAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<ToBeTaskModel.Data.Item, BaseViewHolder>(layoutRes) {
    private var switcherListener: SwitchChangeListener? = null

    override fun convert(helper: BaseViewHolder?, item: ToBeTaskModel.Data.Item?) {
        if (item == null) return
        helper?.apply {
            // setText(R.id.tv_score, item.score)
            setText(R.id.tv_score, "6")
            // setText(R.id.tv_name, "${item.serialno} ${item.categoryname}")
            setText(R.id.tv_name, "01.01.01 专业技能及作业规范")
            // setText(R.id.tv_members, "责任：${item.responsibleName} 配合：${item.cooperatorNames} 特邀：${item.invited}")
            setText(R.id.tv_members, "责任：张三 配合：莉丝 特邀：王五")
            // setText(R.id.tv_type, item.categoryname.replace("/", "-"))
            setText(R.id.tv_type, "露天煤矿-岗位规范-专业技能及作业规范")
            // setText(R.id.tv_serial, "编号：${item.serialno}")
            setText(R.id.tv_serial, "编号：01.01.01")
            // setText(R.id.tv_demand, item.demand)
            setText(R.id.tv_demand, "要求：\n1、建立安全风险管控体系，矿长全面责任制险控管理体系\n2、建立安全风险管控体系，矿长全面责任制险控管理体系\n3、建立安全风险管控体系，矿长全面责任制险控管理体系\n评分:\n1、建立安全风险管控体系，矿长全面责任制险控管理体系\n")
            getView<Switcher>(R.id.iv_switcher).apply {
                update(if (item.state) Switcher.State.ON else Switcher.State.OFF)
                addSwitchChangedListener { switcher, state ->
                    switcherListener?.onChanged(switcher, state, adapterPosition, item)
                }
            }
            val remark = if (item.resultremark.isNullOrBlank()) "" else "意见：${item.resultremark}"
            setText(R.id.tv_opinion, remark)

        }
    }

    fun addSwitchChangeListener(listener: (Switcher, Switcher.State, Int, ToBeTaskModel.Data.Item) -> Unit) {
        switcherListener = object : SwitchChangeListener {
            override fun onChanged(switcher: Switcher, state: Switcher.State, position: Int, item: ToBeTaskModel.Data.Item) {
                listener(switcher, state, position, item)
            }

        }
    }

    interface SwitchChangeListener {
        fun onChanged(switcher: Switcher, state: Switcher.State, position: Int, item: ToBeTaskModel.Data.Item)
    }

}